<script setup>
import { ref } from 'vue'
import { userLoginService } from '@/api/common.js'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

// 登录表单数据
const loginFormModel = ref({
  username: '',
  password: ''
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'onBlur' },
    {
      validator: (val) => val.length >= 5 && val.length <= 20,
      message: '用户名必须是5~20位字符',
      trigger: 'onBlur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'onBlur' },
    {
      pattern: /^\w{4,32}$/,
      message: '密码必须是4~32位的字母、数字、下划线',
      trigger: 'onBlur'
    }
  ]
}

const handleLogin = async () => {
  const res = await userLoginService(loginFormModel.value)
  if (res.data.data.role !== '会员') {
    showNotify({
      type: 'danger',
      message: '登录失败'
    })
    return
  }
  userStore.setUser(res.data.data)
  userStore.setToken(res.data.data.token)
  showNotify({
    type: 'success',
    message: '登录成功'
  })
  router.push('/')
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="header">
      <img class="logo" src="@/assets/logo.png" />
      <h1>会员登录</h1>
    </div>

    <van-form
      class="form"
      @submit="handleLogin"
      :model="loginFormModel"
      :rules="rules"
      validate-trigger="onBlur"
    >
      <van-cell-group inset>
        <van-field
          v-model="loginFormModel.username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="rules.username"
        />
        <van-field
          v-model="loginFormModel.password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="rules.password"
        />
      </van-cell-group>

      <div class="submit-btn">
        <van-button round block type="primary" native-type="submit">登录</van-button>
      </div>
    </van-form>

    <div class="footer">
      <span @click="goToRegister">没有账号？立即注册</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  padding: 0 20px;

  .header {
    text-align: center;
    margin-bottom: 60px;

    .logo {
      width: 150px;
      height: 150px;
    }

    h1 {
      font-size: 24px;
      color: #333;
    }
  }

  .form {
    .submit-btn {
      margin: 40px 0;
    }
  }

  .footer {
    text-align: center;
    margin-top: 30px;

    span {
      color: #1989fa;
      font-size: 14px;
    }
  }
}
</style>
